package tech.yqyl.store;

import cn.hutool.core.text.StrFormatter;
import com.google.common.base.Splitter;
import tech.yqyl.StringUtil;
import tech.yqyl.YamlUtils;
import tech.yqyl.config.LocalStoreConfig;

import java.awt.*;
import java.awt.datatransfer.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Clipboard2FileArticleStore {
    private static String getMarkdown(boolean isMd){
        try{
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

            // 从剪切板中获取数据
            Transferable contents = clipboard.getContents(null);

            // 检查剪切板中是否有 HTML 数据
            if (contents != null && contents.isDataFlavorSupported(DataFlavor.allHtmlFlavor)) {
                // 获取 HTML 格式的数据
                String html = (String) contents.getTransferData(DataFlavor.allHtmlFlavor);
                if( !isMd ) {
                    return html;
                }
                String md = StringUtil.html2Md(html);
                return md;
            } else if( contents!=null && contents.isDataFlavorSupported(DataFlavor.stringFlavor) ) {
                String markdown = (String) contents.getTransferData(DataFlavor.stringFlavor);
                if( !isMd ) {
                    return StringUtil.md2Html(markdown);
                }
                return markdown;
            } else {
                System.out.println("剪切板中没有 HTML 内容。");
            }
        } catch(Exception e){
            System.err.println(StrFormatter.format("当前剪切板没有找到内容异常：{}", e.getMessage()));
        } finally {
        }
        return null;
    }

    public static void store(String title){
        try {
            String markdown = getMarkdown(true);
            LocalStoreConfig config = YamlUtils.getConfig().getLocalStore();
            if( StringUtil.isEmpty(title) ){
                title = Splitter.on("\n").trimResults().omitEmptyStrings().splitToList(markdown).get(0);
            }
            String writeSeriesFilePath = StrFormatter.format("{}/{}/{}.md", config.getBasePath(), config.getTag(), StringUtil.hashString(title));
            // 写入系列文章的 README 文件
            String readmeFile = StrFormatter.format("{}/{}/README.md", config.getBasePath(), config.getTag());
            File readMe = Paths.get(readmeFile).toFile();
            if( !readMe.getParentFile().exists() ) {
                readMe.getParentFile().mkdirs();
            }
            StringBuffer buffer = new StringBuffer("");
            if( !readMe.exists() ) {
                readMe.createNewFile();
                buffer.append(StrFormatter.format("# [{}]({})", config.getTag(), StringUtil.hashString(config.getTag()))).append("\n");
            }
            buffer.append(StrFormatter.format("\n## [{}](./{}.md)", title, StringUtil.hashString(title)));
            Files.write(Paths.get(readmeFile), buffer.toString().getBytes(), StandardOpenOption.APPEND);
            StringUtil.writeMarkdown(writeSeriesFilePath, markdown);
        } catch (IOException e) {
        }
    }

    public static void main(String[] args) {
        YamlUtils.getConfig().getImgBed().setGithubUri("https://raw.githubusercontent.com/qier222/YesPlayMusic/master/");
        Clipboard2FileArticleStore.store("高颜值的第三方网易云播放器");
//        System.out.println(getMarkdown());
//        try {
//            String htmlValue = getMarkdown();
//            File writer = new File("/software/baidupan/0publish/publish.txt");
//            Files.write(writer.toPath(), htmlValue.getBytes());
//        } catch (IOException e) {
//            System.err.println("转换异常!");
//        }
    }

    private static void save2Clipboard(String value) {
        // 获取系统剪切板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 创建一个字符串选择对象
        // 创建一个 Transferable 对象，用于存储 HTML 内容
        Transferable htmlSelection = new Transferable() {
            @Override
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[]{DataFlavor.stringFlavor, DataFlavor.allHtmlFlavor};
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return DataFlavor.stringFlavor.equals(flavor) || DataFlavor.allHtmlFlavor.equals(flavor);
            }

            @Override
            public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                if (isDataFlavorSupported(flavor)) {
                    return value;
                } else {
                    throw new UnsupportedFlavorException(flavor);
                }
            }
        };
        // 将内容设置到剪切板
        clipboard.setContents(htmlSelection, null);
    }
}
